package concurrency;

import java.util.concurrent.SynchronousQueue;

class Customer implements Runnable {
    private static int sCounter = 0;

    private final int mId = sCounter++;

    private final WaitPerson mWaitPerson;

    /**
     * Only one course at a time can be received:
     */
    private SynchronousQueue<Plate> mPlaceSetting = new SynchronousQueue<Plate>();

    public Customer(WaitPerson w) {
        mWaitPerson = w;
    }

    public void deliver(Plate plate) throws InterruptedException {
        // Only blocks if customer is still
        // eating the previous course:
        mPlaceSetting.put(plate);
    }

    @Override
    public void run() {
        for (Course course : Course.values()) {
            Food food = course.randomSelection();
            mWaitPerson.placeOrder(this, food);
            // Blocks until course has been delivered
            try {
                System.out.println(this + "eating " + mPlaceSetting.take());
            } catch (InterruptedException e) {
                System.out.println(this + "waiting for " + course + " interrupted");
                break;
            }
        }
        System.out.println(this + "finished meal, leaving");
    }

    @Override
    public String toString() {
        return "Customer_" + mId + " ";
    }
}
